/**
 *  This file is part of TaoBaoItemImporter.
 *
 *   TaoBaoItemImporter is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   TaoBaoItemImporter is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with TaoBaoItemImporter.  If not, see <http://www.gnu.org/licenses/>. 
 */
package com.googlecode.ulysses.taobao.synchronization;

import java.util.*;
import com.mongodb.*;

import com.googlecode.ulysses.taobao.BackDBWriter;
import com.googlecode.ulysses.taobao.Constants;

/**
 * 
 * @author Hegen <lhegen@gmail.com>
 *
 */
public class CategoryWriter implements BackDBWriter {
	private DBCollection srccoll;
	private DBCollection dstcoll;
	
	public CategoryWriter(DBCollection srccoll, DBCollection dstcoll){
		this.srccoll = srccoll;
		this.dstcoll = dstcoll;
	}

	public void updateCategoryDBs(int id, String name, int child) throws MongoException{
		// TODO Auto-generated method stub
		BasicDBObject query = new BasicDBObject();
		query.put("cat_id", id);
		//query.put("cat_name", name);
		
		//Result number, if count equal one we need insert child into sub_cat field;
		//if count equal zero, we create a new category document, otherwise println out error message 
		long count  = dstcoll.count(query);
		if(count == 1){
			BasicDBObject update = new BasicDBObject();
			update.put("$addToSet", new BasicDBObject("sub_cats", child));
			dstcoll.update(query, update);
		}
		else if(count == 0){
			BasicDBObject doc = new BasicDBObject();
			doc.put("cat_id", id);
			doc.put("cat_name", name);
			
			ArrayList<Integer> sub_cats = new ArrayList<Integer>();
			sub_cats.add(child);
			doc.put("sub_cats",sub_cats);
			
			dstcoll.insert(doc);
		}
		else {
			System.err.println(count + " elements have the same id and name in this collection");
		}
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.googlecode.ulysses.taobao.BackDBWriter#writeCategoryDB()
	 */
	@Override
	public void writeCategoryDB(){
		DBCursor cursor = srccoll.find();
		BasicDBObject media = new BasicDBObject();
		int id;
		String name;
		int child;
		while(cursor.hasNext()){
			media = (BasicDBObject)cursor.next();
			id = media.getInt("item_main_cats");
			name = Constants.DEFAULT_CATEGORY_NAME;
			child = media.getInt("item_sub_cats");
			
			updateCategoryDBs(id, name, child);
		}
	}

}
